package android.SettingsTest;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class SettingsTest extends Activity {
	
	private static final String LOG_TAG = "DroidGap";
	private WebView appView;
	private Settings gap;
	private XmlReader xml;
	
    /** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); 
        setContentView(R.layout.main);        
         
        appView = (WebView) findViewById(R.id.appView);
        
        /* This changes the setWebChromeClient to log alerts to LogCat!  Important for Javascript Debugging */
        
        appView.setWebChromeClient(new MyWebChromeClient());
        appView.getSettings().setJavaScriptEnabled(true);
        appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);        
        
        /* Bind the appView object to the gap class methods */
        File f = new File("data/data/android.SettingsTest/files/preferences.xml");  //daar nog zetten, zie assets folder!!
        xml = new XmlReader(f);
		bindBrowser(appView, f);
   
        //appView.loadUrl("");
		String mimeType = "text/html";
		String encoding = "utf-8";
        appView.loadDataWithBaseURL("Settings://widgetnaam", generateSettings(f), mimeType, encoding, null);
        
    }
	
	private String generateSettings(File f) {
		HashMap<String, String> hash = xml.read();
		Set<String> keys = hash.keySet();
		
		String html = "";
		html += "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
		html += "<html xmlns='http://www.w3.org/1999/xhtml'>";
		html += "<head>";
		html += "<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>";
		html += "<title>Settings</title>";
		html += "</head>";
		html += "<script>";
		html += "function init(){";
		
	    Iterator <String> it = keys.iterator();
	    while (it.hasNext()) {
	        // Get element
	    	String v = it.next();
	        html += "document.getElementById('" + v + "').value = window.DroidGap.getValue('" + v + "');";
	    }

		
		html += "}";
		html += "function updateSettings(){";
		
	    it = keys.iterator();
	    while (it.hasNext()) {
	        // Get element
	    	String v = it.next();
	        html += "window.DroidGap.setValue('" + v + "', document.getElementById('" + v + "').value );";
	    }
		
		html += "window.DroidGap.update();";
		html += "}";
		html += "</script>";
		
		html += "<body onload='init();'>";
		html += "<div class='toolbar'> <h1 id='pageTitle'>Settings</h1> </div>";
		html += "<div id='settings' title='Settings' class='panel'>";
		html += "<fieldset>";
		
		html += "<div class='row'>";
		
	    it = keys.iterator();
	    while (it.hasNext()) {
	        // Get element
	    	String v = it.next();
	        html += "<label>" + v + "</label>";
	        html += "<input  name='" + v.toUpperCase() + "' id='" + v + "' value='' type='text'/>";
	    }
		html += "</div>  ";
		
		html += "<div class='row'>";
		html += "<a class='button blueButton' type='submit' onclick='updateSettings();'>Update Settings</a>";
		html += "<br/>";
		html += "<a class='button blueButton' type='submit' onclick='init();'>Reset Settings</a>";
		html += "</div> ";		
		
		html += "</fieldset>";
		html += "</div>";
		html += "</body>";
		html += "</html>";
		return html;
	}

	@Override
    public void onConfigurationChanged(Configuration newConfig) {
      //don't reload the current page when the orientation is changed
      super.onConfigurationChanged(newConfig);
    } 
    
    private void bindBrowser(WebView appView, File f)
    {
			//FileInputStream fIn = openFileInput("preferences.xml");
			//FileOutputStream fOut = openFileOutput("preferences1.xml",MODE_PRIVATE); 
			gap = new Settings(f);
			appView.addJavascriptInterface(gap, "DroidGap");
			
			HashMap<String, String> hash = xml.read();
			gap.setText(hash);
    }
    
    /**
     * Provides a hook for calling "alert" from javascript. Useful for
     * debugging your javascript.
     */
    final class MyWebChromeClient extends WebChromeClient {
    	@Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(LOG_TAG, message);
            result.confirm();
            return true;
        }
    }
    
}